package com.example.myapplication.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class MyViewModel: ViewModel(){
    //在MyViewModel内部使用，可以更新数据
    private var _state:MutableStateFlow<Int> = MutableStateFlow(0)

    //不可变的流，用于公开给UI获取数据使用
    val state: StateFlow<Int> = _state

    //counter自增
    fun increment(){
        _state.value ++
    }

    //counter自减
    fun decrement(){
        if (_state.value>0){
            _state.value--
        }
    }
}



@Composable
fun ViewModelCounter(padding: PaddingValues,viewModel: MyViewModel= viewModel()) {
    val state = viewModel.state.collectAsState()
    //定义可观察的状态变量，并使用remember记住该状态；
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = Modifier
            .background(Color.Yellow)
            .fillMaxWidth()
            .padding(padding)
    ) {
        Text(text = "当前计数：${state.value}", fontSize = 24.sp)

        Row {
            Button(onClick = { viewModel.increment() }, modifier = Modifier.padding(8.dp)) {
                Text("增加")
            }
            Button(onClick = { viewModel.decrement() }, modifier = Modifier.padding(8.dp)) {
                Text("减少")
            }
        }
    }
}

@Composable
fun ViewModelCounterContainer(padding: PaddingValues){
    var flag by rememberSaveable { mutableStateOf(true) }
    Column(
        modifier = Modifier.fillMaxSize()
            .padding(padding)
    ) {
        if (flag){
            ViewModelCounter(padding)
        }

        Button(onClick = {
            flag= !flag
        }) {
            Text("隐藏显示计数器")
        }
    }
}